/********************************************
 * 功能说明: Web端Project基础业务控制器
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员:
 * 开发时间: 2019-12-18 18:41:08
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.web.controller;

import com.codahale.metrics.annotation.Timed;
import com.querydsl.core.types.Predicate;
import com.spring.arch.common.dto.result.PageResultDTO;
import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.enums.ProjectStatus;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.uaa.web.converter.WebProjectConverter;
import com.spring.arch.uaa.web.dto.WebProjectDTO;
import com.spring.arch.common.dto.result.PageResultDTO;
import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.enums.ProjectStatus;
import com.spring.arch.uaa.model.Project;
import com.spring.arch.uaa.repository.ProjectRepository;
import com.spring.arch.uaa.service.ProjectService;
import com.spring.arch.uaa.web.converter.WebProjectConverter;
import com.spring.arch.uaa.web.dto.WebProjectDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.UUID;

import static com.spring.arch.uaa.errorcode.UaaErrorCode.E2001002001;


/**
 * Web端Project基础业务控制器
 * @author
 * @version 1.0.0.1
 * @since 2019-12-18 18:41:08
 */
@Slf4j
@RestController
@RequestMapping(value = "/uaa/w/project", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = {"Web端Project管理API" })
public class WebProjectController {

    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private WebProjectConverter projectConverter;

    /**
     * 新建操作
     *
     * @param projectDTO 新建项目资源的DTO
     * @return 新建资源
     */
    @Timed
    @ApiOperation(value = "新建项目操作")
    @PostMapping
    public ResultDTO<WebProjectDTO> create(@RequestBody @Valid final WebProjectDTO projectDTO) {
        //先新增组织，再新增项目
        projectDTO.setStatus(ProjectStatus.NEW);
        Project model = this.projectConverter.toModel(projectDTO);
        model = this.projectService.save(model);
        this.projectService.buildDatasource(model);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was created.", Project.class.getSimpleName(), model.getId());
        }
        return this.projectConverter.toResultDTO(model);
    }

    /**
     * 删除操作
     *
     * @param id 实体对象ID
     * @return 操作结果
     */
    @Timed
    @ApiOperation(value = "删除操作")
    @DeleteMapping(value = "/{id}")
    public ResultDTO<Void> delete(@PathVariable final UUID id) {
        this.projectService.delete(id);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was disable.", Project.class.getSimpleName(), id);
        }
        return ResultDTO.success();
    }

    /**
     * 更新操作
     *
     * @param id 实体对象ID
     * @param projectDTO 更新资源的DTO
     * @return 更新后资源
     */
    @Timed
    @ApiOperation(value = "更新操作")
    @PutMapping(value = "/{id}")
    public ResultDTO<WebProjectDTO> update(@PathVariable final UUID id, @RequestBody @Valid final WebProjectDTO projectDTO) {
        projectDTO.setId(id);
        final Project model = this.projectConverter.toModel(projectDTO);
        //只更新地址、类型、区域信息、备注等
        this.projectService.update(model);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was updated.", Project.class.getSimpleName(), model.getId());
        }
        return this.projectConverter.toResultDTO(model);
    }


    /**
     * 项目失败更新
     *
     * @param code 实体对象ID
     * @return 更新后资源
     */
    @Timed
    @ApiOperation(value = "项目失败更新")
    @GetMapping(value = "/failure/{code}")
    public ResultDTO<WebProjectDTO> failure(@PathVariable final String code) {
        if (!this.projectRepository.existsByCode(code)) {
            throw ExceptionHolder.serviceException(UaaErrorCode.E2001002001, code);
        }
        Project model = this.projectRepository.findByCode(code);
        model.setStatus(ProjectStatus.FAILURE);
        model = this.projectRepository.save(model);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was failure.", Project.class.getSimpleName(), model.getId());
        }
        return this.projectConverter.toResultDTO(model);
    }

    /**
     * 项目成功更新
     *
     * @param schema 实体对象ID
     * @return 更新后资源
     */
    @Timed
    @ApiOperation(value = "项目成功更新")
    @GetMapping(value = "/online/{schema}")
    public ResultDTO<WebProjectDTO> online(@PathVariable final String schema) {
        if (!this.projectRepository.existsByCode(schema)) {
            throw ExceptionHolder.serviceException(UaaErrorCode.E2001002001, schema);
        }
        Project model = this.projectRepository.findByCode(schema);
        model.setStatus(ProjectStatus.ONLINE);
        model = this.projectRepository.save(model);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was online.", Project.class.getSimpleName(), model.getId());
        }
        return this.projectConverter.toResultDTO(model);
    }

    /**
     * 项目下线更新
     *
     * @param code 实体对象ID
     * @return 更新后资源
     */
    @Timed
    @ApiOperation(value = "项目下线更新")
    @GetMapping(value = "/offline/{code}")
    public ResultDTO<WebProjectDTO> offline(@PathVariable final String code) {
        if (!this.projectRepository.existsByCode(code)) {
            throw ExceptionHolder.serviceException(UaaErrorCode.E2001002001, code);
        }
        Project model = this.projectRepository.findByCode(code);
        model.setStatus(ProjectStatus.FAILURE);
        model = this.projectRepository.save(model);
        this.projectService.update(model);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was offline.", Project.class.getSimpleName(), model.getId());
        }
        return this.projectConverter.toResultDTO(model);
    }

    /**
     * 获取分页数据
     *
     * @param pageable 分页+排序参数
     * @return 分页数据
     */
    @Timed
    @ApiOperation(value = "获取分页数据")
    @PostMapping(value = "/s")
    public PageResultDTO<WebProjectDTO> search(@PageableDefault(sort = {"createdDate"}, direction = Sort.Direction.DESC) final Pageable pageable,
                                               @QuerydslPredicate(root = Project.class) Predicate predicate) {
        final Page<Project> models = this.projectRepository.findAll(predicate, pageable);
        return this.projectConverter.toResultDTO(models);
    }

    /**
     * 取得详细数据
     *
     * @param id 实体对象ID
     * @return 资源详细
     */
    @Timed
    @ApiOperation(value = "获取详细数据")
    @GetMapping(value = "/{id}")
    public ResultDTO<WebProjectDTO> get(@PathVariable final UUID id) {
        final Project model = this.projectRepository.findById(id)
                .orElseThrow(() -> ExceptionHolder.serviceException(UaaErrorCode.E2001002001, Project.class.getSimpleName()));
        return this.projectConverter.toResultDTO(model);
    }
}
